#!/usr/local/bin/python3
# -*- coding: UTF-8 -*- 

from Core.exportNodesFile import exportNodesFile
from Core.makeNodesFile import *
# from Common.splitString import splitStringByIndex
# from Common.splitString import splitString
from Map.test import *
from Template.CommonTemplate.CommonTemplate import *
from Template.ThreePalaceTemplate.ThreePalaceTemplate import *

import sys
import os
import json

import shutil
import zipfile
import time

def insertString(oriStr,repStr,contentStr): #在指定字符串后面添加字符串
    pos = oriStr.find(repStr)
    resultStr = ""
    strLen = len(repStr)
    if pos != -1:
        resultStr = oriStr[:(pos+strLen)] +"\n\n" +contentStr +"\n" + oriStr[(pos+strLen):]
    return  resultStr

def createPalace(dataDic,jsonData):
    
    # baseFile = open("./baseFunction.lua",'r')
    # resultString = baseFile.read()
    # baseFile.close()
    if(data_dict["type"]=="palace_3*1"):
            print(jsonData)
            template=ThreePalaceTemplate(jsonData)
            template.CreateIndexAndMetadataJson()
            template.CopySpecificResource()
            # 创建node拷贝资源    
            template.createAndCopyNodesResource(jsonData)
    #    tOutPutPath(),template.getSourcePath()) #返回元祖，包括内容和index路径
def copyResourceFile(oriRes,desRes):
    if not  os.path.isdir(oriRes):
        print("源目录不存在")
        return -1
    if not os.path.exists(desRes):
        os.makedirs(desRes)
    listName = os.listdir(oriRes)
    for name in listName:
        sourceAbs = os.path.join(oriRes,name)
        targetAbs = os.path.join(desRes,name)
        if os.path.isdir(sourceAbs):
            #创建目标目录
            if not os.path.exists(targetAbs):
                os.makedirs(targetAbs)
            copyDir(sourceAbs,targetAbs)
        if os.path.isfile(sourceAbs):
            # 1.如果目标子级文件不存在  或者 目标子级文件存在但是该文件与原子级文件大小不一致   则需要复制
            if (not os.path.exists(targetAbs))  or  (os.path.exists(targetAbs) and os.path.getsize(targetAbs) != os.path.getsize(sourceAbs)):
                rf = open(sourceAbs,mode="rb")
                wf = open(targetAbs,mode="wb")
                while True:
                    content = rf.read(1024*1024*10)
                    if len(content) == 0:
                        break
                    wf.write(content)
                    wf.flush()
                rf.close()
                wf.close()

if __name__ == "__main__":

    #workpath = os.getcwd()
    data_dict={}  #创建一个空字典，盛放配置文件
    #templateContent = ()
    #调用模版文件生成字符串，然后拼接写进lua文件
    with open("config.json",'r') as load_f:
        data_dict = json.load(load_f)
      #  print(data_dict["otherResourcesExist"])
        data_array = data_dict["zippath"]
        templetePath =  data_dict["type"]+"Template"
        modulePath="Template."+str(templetePath)+"."+str(templetePath)
        print(templetePath)
        print(modulePath)
    try:
        module=__import__(modulePath)
    except ModuleNotFoundError:
        print("找不到"+templetePath+"模版类")
        print("模版类等于type+Template")
        exit(0)
    else:
        print("success")
        module=__import__(modulePath)
        firstsubModule=getattr(module, templetePath)
        secondsubModule=getattr(firstsubModule, templetePath)
        templateName=getattr(secondsubModule, templetePath)
        print(templateName)
        if hasattr(templateName, '__init__'):
            template=templateName(data_array)
            template.CreateIndexAndMetadataJson()
            template.CopySpecificResource()
            # 创建node拷贝资源    
            template.createAndCopyNodesResource(data_array)
           #print(template.getOutPutPath)
            pass
        else:
            print("找不到相应的类")
            exit(0)

    
        # elif(data_dict["type"]=="手势"):
        #     pass
        # else:
        #     pass

#   template=ThreePalaceTemplate(zipPath)
#     template.CreateIndexAndMetadataJson()
#     template.CopySpecificResource()
#     # 创建node拷贝资源    
#     template.createAndCopyNodesResource(zipPath)

    # metadataflie=open(templateContent[1]+"/metadata.json", "w+")
    # metadatastring='{"script": "index.lua", "nodes": [], "extensions:": ["KuruFaceDetector"]}'
    # metadataflie.write(metadatastring)
    # metadataflie.flush()
    # metadataflie.close()

    # indexPath = templateContent[1]+"/index.lua"
    # print(indexPath)
    # indexfile = open( indexPath, "w+" ) #打开index文件
    # indexfile.write(templateContent[0])
    # indexfile.flush()
    # indexfile.close()    

    #拷贝资源
    # if data_dict["otherResourcesExist"] :
    #     copyResourceFile(templateContent[2],templateContent[1])
    
    
 


    #拷贝文件
    